package com.cencat.route.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cencat.route.entity.Driver;
import com.cencat.route.mapper.DriverMapper;
import com.cencat.route.service.DriverService;
import com.cencat.route.vo.DriverVO;
import com.cencat.route.dto.DriverDTO;
import com.cencat.route.dto.DriverQueryDTO;
import com.cencat.route.dto.DriverBatchUpdateDTO;
import com.cencat.route.dto.DriverStatisticsDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 司机管理服务实现类
 * 提供司机的增删改查、统计分析、智能匹配等功能的具体实现
 * 
 * @author cencat
 * @version 1.0
 * @since 2025-01-20
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DriverServiceImpl implements DriverService {

    @Autowired
    private DriverMapper driverMapper;

    @Override
    public Page<DriverVO> getDriverList(Page<Driver> page, DriverQueryDTO queryDTO) {
        Page<Driver> driverPage = driverMapper.selectDriverPage(page, queryDTO);
        Page<DriverVO> voPage = new Page<>(driverPage.getCurrent(), driverPage.getSize(), driverPage.getTotal());
        
        List<DriverVO> voList = driverPage.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        voPage.setRecords(voList);
        
        return voPage;
    }

    @Override
    public DriverVO getDriverById(Long id) {
        Driver driver = driverMapper.selectById(id);
        return driver != null ? convertToVO(driver) : null;
    }

    @Override
    public Boolean createDriver(DriverDTO driverDTO) {
        // 检查司机编号是否已存在
        if (existsByDriverNo(driverDTO.getDriverNo(), null)) {
            throw new RuntimeException("司机编号已存在: " + driverDTO.getDriverNo());
        }
        
        // 检查身份证号是否已存在
        if (existsByIdCard(driverDTO.getIdCard(), null)) {
            throw new RuntimeException("身份证号已存在: " + driverDTO.getIdCard());
        }
        
        // 检查手机号是否已存在
        if (existsByPhone(driverDTO.getPhone(), null)) {
            throw new RuntimeException("手机号已存在: " + driverDTO.getPhone());
        }
        
        Driver driver = convertToEntity(driverDTO);
        driver.setCreateTime(LocalDateTime.now());
        driver.setUpdateTime(LocalDateTime.now());
        
        return driverMapper.insert(driver) > 0;
    }

    @Override
    public Boolean updateDriver(Long id, DriverDTO driverDTO) {
        Driver existingDriver = driverMapper.selectById(id);
        if (existingDriver == null) {
            throw new RuntimeException("司机不存在: " + id);
        }
        
        // 检查司机编号是否已存在（排除当前记录）
        if (existsByDriverNo(driverDTO.getDriverNo(), id)) {
            throw new RuntimeException("司机编号已存在: " + driverDTO.getDriverNo());
        }
        
        // 检查身份证号是否已存在（排除当前记录）
        if (existsByIdCard(driverDTO.getIdCard(), id)) {
            throw new RuntimeException("身份证号已存在: " + driverDTO.getIdCard());
        }
        
        // 检查手机号是否已存在（排除当前记录）
        if (existsByPhone(driverDTO.getPhone(), id)) {
            throw new RuntimeException("手机号已存在: " + driverDTO.getPhone());
        }
        
        Driver driver = convertToEntity(driverDTO);
        driver.setId(id);
        driver.setUpdateTime(LocalDateTime.now());
        
        return driverMapper.updateById(driver) > 0;
    }

    @Override
    public Boolean deleteDriver(Long id) {
        Driver driver = driverMapper.selectById(id);
        if (driver == null) {
            throw new RuntimeException("司机不存在: " + id);
        }
        
        return driverMapper.deleteById(id) > 0;
    }

    @Override
    public Boolean batchDeleteDrivers(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return false;
        }
        
        return driverMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Boolean batchUpdateDriverStatus(DriverBatchUpdateDTO batchUpdateDTO) {
        if (CollectionUtils.isEmpty(batchUpdateDTO.getIds())) {
            return false;
        }
        
        return driverMapper.batchUpdateDriverStatus(
                batchUpdateDTO.getIds(), 
                batchUpdateDTO.getStatus()
        ) > 0;
    }

    @Override
    public Boolean batchUpdateCreditScore(List<Long> ids, Integer creditScore) {
        if (CollectionUtils.isEmpty(ids)) {
            return false;
        }
        
        return driverMapper.batchUpdateCreditScore(ids, creditScore) > 0;
    }

    @Override
    public Boolean batchUpdateLocation(List<Long> ids, String longitude, String latitude) {
        if (CollectionUtils.isEmpty(ids)) {
            return false;
        }
        
        return driverMapper.batchUpdateLocation(ids, longitude, latitude) > 0;
    }

    @Override
    public Map<String, Object> getDriverStatistics(DriverStatisticsDTO statisticsDTO) {
        Map<String, Object> result = new HashMap<>();
        
        // 总司机数
        Long totalCount = driverMapper.selectCount(null);
        result.put("totalCount", totalCount);
        
        // 在线司机数
        Long onlineCount = driverMapper.countByStatus("ONLINE");
        result.put("onlineCount", onlineCount);
        
        // 离线司机数
        Long offlineCount = driverMapper.countByStatus("OFFLINE");
        result.put("offlineCount", offlineCount);
        
        // 忙碌司机数
        Long busyCount = driverMapper.countByStatus("BUSY");
        result.put("busyCount", busyCount);
        
        // 已认证司机数
        Long verifiedCount = driverMapper.countByVerificationStatus("VERIFIED");
        result.put("verifiedCount", verifiedCount);
        
        // 待认证司机数
        Long pendingCount = driverMapper.countByVerificationStatus("PENDING");
        result.put("pendingCount", pendingCount);
        
        return result;
    }

    @Override
    public List<DriverVO> getOnlineDrivers(Integer limit) {
        List<Driver> drivers = driverMapper.selectOnlineDrivers(limit);
        return drivers.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<DriverVO> getAvailableDrivers(Integer limit) {
        List<Driver> drivers = driverMapper.selectAvailableDrivers(limit);
        return drivers.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<DriverVO> getBusyDrivers(Integer limit) {
        List<Driver> drivers = driverMapper.selectBusyDrivers(limit);
        return drivers.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<DriverVO> getHighRatedDrivers(Integer minRating, Integer limit) {
        List<Driver> drivers = driverMapper.selectHighRatedDrivers(minRating, limit);
        return drivers.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<DriverVO> getNewRegisteredDrivers(Integer days, Integer limit) {
        LocalDateTime startTime = LocalDateTime.now().minusDays(days);
        List<Driver> drivers = driverMapper.selectNewRegisteredDrivers(startTime, limit);
        return drivers.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<DriverVO> getVerifiedDrivers(Integer limit) {
        List<Driver> drivers = driverMapper.selectVerifiedDrivers(limit);
        return drivers.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<DriverVO> getPendingVerificationDrivers(Integer limit) {
        List<Driver> drivers = driverMapper.selectPendingVerificationDrivers(limit);
        return drivers.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<DriverVO> getNearbyDrivers(String longitude, String latitude, Double radius, Integer limit) {
        List<Driver> drivers = driverMapper.selectNearbyDrivers(longitude, latitude, radius, limit);
        return drivers.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<DriverVO> getDriversByVehicleType(String vehicleType, String status, Integer limit) {
        List<Driver> drivers = driverMapper.selectDriversByVehicleType(vehicleType, status, limit);
        return drivers.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<DriverVO> intelligentMatchDrivers(Long routeId, Integer limit) {
        // 智能匹配司机逻辑
        List<Driver> drivers = driverMapper.selectIntelligentMatchDrivers(routeId, limit);
        return drivers.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public Boolean existsById(Long id) {
        return driverMapper.selectById(id) != null;
    }

    @Override
    public Boolean existsByDriverNo(String driverNo, Long excludeId) {
        return driverMapper.existsByDriverNo(driverNo, excludeId) > 0;
    }

    @Override
    public Boolean existsByIdCard(String idCard, Long excludeId) {
        return driverMapper.existsByIdCard(idCard, excludeId) > 0;
    }

    @Override
    public Boolean existsByPhone(String phone, Long excludeId) {
        return driverMapper.existsByPhone(phone, excludeId) > 0;
    }

    @Override
    public Boolean existsByLicenseNo(String licenseNo, Long excludeId) {
        return driverMapper.existsByLicenseNo(licenseNo, excludeId) > 0;
    }

    @Override
    public Boolean registerDriver(DriverDTO driverDTO) {
        // 司机注册逻辑
        driverDTO.setStatus("PENDING");
        driverDTO.setVerificationStatus("PENDING");
        return createDriver(driverDTO);
    }

    @Override
    public Boolean verifyDriver(Long driverId, Map<String, Object> verificationData) {
        Driver driver = driverMapper.selectById(driverId);
        if (driver == null) {
            throw new RuntimeException("司机不存在: " + driverId);
        }
        
        // 更新认证状态
        driver.setVerificationStatus("VERIFIED");
        driver.setVerificationTime(LocalDateTime.now());
        driver.setUpdateTime(LocalDateTime.now());
        
        return driverMapper.updateById(driver) > 0;
    }

    @Override
    public Boolean activateDriver(Long driverId) {
        Driver driver = driverMapper.selectById(driverId);
        if (driver == null) {
            throw new RuntimeException("司机不存在: " + driverId);
        }
        
        driver.setStatus("ACTIVE");
        driver.setUpdateTime(LocalDateTime.now());
        
        return driverMapper.updateById(driver) > 0;
    }

    @Override
    public Boolean deactivateDriver(Long driverId, String reason) {
        Driver driver = driverMapper.selectById(driverId);
        if (driver == null) {
            throw new RuntimeException("司机不存在: " + driverId);
        }
        
        driver.setStatus("INACTIVE");
        driver.setUpdateTime(LocalDateTime.now());
        
        return driverMapper.updateById(driver) > 0;
    }

    @Override
    public Boolean suspendDriver(Long driverId, String reason, Integer suspendDays) {
        Driver driver = driverMapper.selectById(driverId);
        if (driver == null) {
            throw new RuntimeException("司机不存在: " + driverId);
        }
        
        driver.setStatus("SUSPENDED");
        driver.setUpdateTime(LocalDateTime.now());
        
        return driverMapper.updateById(driver) > 0;
    }

    @Override
    public Boolean unsuspendDriver(Long driverId) {
        Driver driver = driverMapper.selectById(driverId);
        if (driver == null) {
            throw new RuntimeException("司机不存在: " + driverId);
        }
        
        driver.setStatus("ACTIVE");
        driver.setUpdateTime(LocalDateTime.now());
        
        return driverMapper.updateById(driver) > 0;
    }

    @Override
    public Boolean updateDriverLocation(Long driverId, String longitude, String latitude) {
        return driverMapper.updateDriverLocation(driverId, longitude, latitude) > 0;
    }

    @Override
    public Boolean updateDriverStatus(Long driverId, String status) {
        Driver driver = driverMapper.selectById(driverId);
        if (driver == null) {
            throw new RuntimeException("司机不存在: " + driverId);
        }
        
        driver.setStatus(status);
        driver.setUpdateTime(LocalDateTime.now());
        
        return driverMapper.updateById(driver) > 0;
    }

    @Override
    public Boolean updateCreditScore(Long driverId, Integer creditScore, String reason) {
        return driverMapper.updateCreditScore(driverId, creditScore, reason) > 0;
    }

    @Override
    public Map<String, Object> getDriverPerformance(Long driverId, LocalDateTime startTime, LocalDateTime endTime) {
        Map<String, Object> result = new HashMap<>();
        
        // 获取司机绩效数据
        // 这里可以调用其他服务获取订单、评价等数据
        result.put("driverId", driverId);
        result.put("period", startTime + " - " + endTime);
        result.put("totalOrders", 0);
        result.put("completedOrders", 0);
        result.put("cancelledOrders", 0);
        result.put("averageRating", 0.0);
        result.put("totalIncome", 0.0);
        
        return result;
    }

    @Override
    public List<DriverVO> exportDrivers(DriverQueryDTO queryDTO) {
        List<Driver> drivers = driverMapper.selectDriverList(queryDTO);
        return drivers.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public Boolean importDrivers(List<DriverDTO> drivers) {
        if (CollectionUtils.isEmpty(drivers)) {
            return false;
        }
        
        for (DriverDTO driverDTO : drivers) {
            try {
                createDriver(driverDTO);
            } catch (Exception e) {
                // 记录导入失败的记录
                System.err.println("导入司机失败: " + driverDTO.getDriverNo() + ", 原因: " + e.getMessage());
            }
        }
        
        return true;
    }

    @Override
    public Boolean syncDriverData(Long driverId, String syncType) {
        // 司机数据同步逻辑
        Driver driver = driverMapper.selectById(driverId);
        if (driver == null) {
            return false;
        }
        
        // 根据同步类型执行不同的同步逻辑
        switch (syncType) {
            case "LOCATION":
                // 同步位置信息
                break;
            case "STATUS":
                // 同步状态信息
                break;
            case "VEHICLE":
                // 同步车辆信息
                break;
            default:
                // 全量同步
                break;
        }
        
        return true;
    }

    @Override
    public Boolean batchSyncDriverData(List<Long> driverIds, String syncType) {
        if (CollectionUtils.isEmpty(driverIds)) {
            return false;
        }
        
        for (Long driverId : driverIds) {
            syncDriverData(driverId, syncType);
        }
        
        return true;
    }

    /**
     * 将Driver实体转换为DriverVO
     */
    private DriverVO convertToVO(Driver driver) {
        if (driver == null) {
            return null;
        }
        
        DriverVO vo = new DriverVO();
        BeanUtils.copyProperties(driver, vo);
        return vo;
    }

    /**
     * 将DriverDTO转换为Driver实体
     */
    private Driver convertToEntity(DriverDTO dto) {
        if (dto == null) {
            return null;
        }
        
        Driver entity = new Driver();
        BeanUtils.copyProperties(dto, entity);
        return entity;
    }
}